package com.weimob.cloud.api.token.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.weimob.cloud.api.config.WeimobAccessTokenStorageConfig;
import com.weimob.cloud.api.config.WeimobCloudConfig;
import com.weimob.cloud.api.exception.WeimobApiException;
import com.weimob.cloud.api.token.client.WeimobAccessTokenClient;
import com.weimob.cloud.api.token.rsp.WeimobAccessTokenRsp;
import com.weimob.cloud.api.token.service.WeimobTokenService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RequiredArgsConstructor
public class WeimobTokenServiceImpl implements WeimobTokenService {

    private final WeimobAccessTokenStorageConfig weimobAccessTokenStorageConfig;
    private final WeimobAccessTokenClient weimobAccessTokenClient;
    private final WeimobCloudConfig weimobCloudConfig;

    @Override
    public String getAccessToken() {
        String accessToken = weimobAccessTokenStorageConfig.getAccessToken();
        if (StrUtil.isNotBlank(accessToken)) {
            return accessToken;
        }

        synchronized (this) {
            if (StrUtil.isBlank(accessToken)) {
                WeimobAccessTokenRsp accessTokenRsp = weimobAccessTokenClient.accessToken(weimobCloudConfig.getClientId(),
                        weimobCloudConfig.getClientSecret(),
                        weimobCloudConfig.getShopId());
                log.info("微盟access token接口响应: {}", JSON.toJSONString(accessTokenRsp));
                if (accessTokenRsp != null && StrUtil.isNotBlank(accessTokenRsp.getAccessToken())) {
                    weimobAccessTokenStorageConfig.setAccessToken(accessTokenRsp);
                    accessToken = accessTokenRsp.getAccessToken();
                } else {
                    throw new WeimobApiException("获取微盟access token失败");
                }
            }
        }

        return accessToken;
    }
}
